package com.cuit.qx.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cuit.qx.aop.OperLog;
import com.cuit.qx.bean.WarnSound;
import com.cuit.qx.service.WarnSoundService;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import static org.thymeleaf.util.ListUtils.isEmpty;

/**
 * @Title: Controller
 * @Description: 预警声音管理
 * @Author: wk
 * @Date; 2021/2/2
 * @Version: V1.0
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/warnSound")
public class WarnSoundController {

    @Autowired
    private WarnSoundService warnSoundService;

    @Value("${uploadWarnSoundUrl}")
    private String uploadWarnSoundUrl;
    @Value("${ip}")
    private String ip;
    @Value("${upload}")
    private String upload;
    @Value("${server.port}")
    private String port;


    /**
     * 分页查询全部预警音乐数据
     *
     * @param pageNo   当前页数
     * @param pageSize 每页条数
     * @return
     */
    @RequestMapping(value = "/getWarnSoundList", method = RequestMethod.GET)
    @OperLog(operModul = "预警音乐管理", operType = "1", operDesc = "分页查询全部预警音乐数据")
    @ResponseBody
    public ReturnData getWarningList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {

        IPage<WarnSound> warnSoundList = warnSoundService.getWarnSoundList(pageNo, pageSize);
        if (!isEmpty(warnSoundList.getRecords())) {
            // 将long类型转为Integer
            long total = warnSoundList.getTotal();
            String str = String.valueOf(total);
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), Integer.parseInt(str), warnSoundList.getRecords());
        } else {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEEBUT.getMsg(), (int) warnSoundList.getTotal(), new ArrayList());
        }
    }

    /**
     * 新增预警声音
     *
     * @param warnSound
     * @return
     */
    @RequestMapping(value = "/addWarnSound", method = RequestMethod.POST)
    @ResponseBody
    @OperLog(operModul = "预警音乐管理", operType = "2", operDesc = "新增预警声音")
    public ReturnData addWarnSound(@RequestBody WarnSound warnSound) {
        int state = warnSoundService.insertWarnSound(warnSound);
        if (state > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), warnSound);
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }

    /**
     * 修改预警声音
     *
     * @param warnSound
     * @return
     */
    @RequestMapping(value = "/updateWarnSound", method = RequestMethod.POST)
    @ResponseBody
    @OperLog(operModul = "预警音乐管理", operType = "2", operDesc = "修改预警声音")
    public ReturnData updateWarnSound(@RequestBody WarnSound warnSound) {
        int state = warnSoundService.updateWarnSound(warnSound);
        if (state > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg(), warnSound);
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }

    /**
     * 根据预警id删除预警音乐
     *
     * @param id 预警id
     * @return
     */
    @RequestMapping(value = "/deleteWarnSoundById", method = RequestMethod.GET)
    @OperLog(operModul = "预警音乐管理", operType = "4", operDesc = "根据预警id删除预警音乐")
    @ResponseBody
    public ReturnData deleteWarnSoundById(String id) {
        WarnSound warnSound = warnSoundService.getById(id);
        String path = warnSound.getPath();
        String[] split = path.split("/");
        String fileName = split[split.length - 1];

        File newFile = new File(uploadWarnSoundUrl + File.separator + fileName);
        newFile.delete();

        boolean flag = warnSoundService.removeById(id);
        if (flag) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
        } else {
            return new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }


    /**
     * 修改某条预警声音状态
     *
     * @param id 预警id
     * @return
     */
    @RequestMapping(value = "/updateWarnSoundStatus", method = RequestMethod.GET)
    @ResponseBody
    @OperLog(operModul = "预警音乐管理", operType = "2", operDesc = "修改某条预警声音状态")
    public ReturnData updateWarnSoundStatus(String id) {
        List<WarnSound> warnSounds = warnSoundService.list();
        for (WarnSound warnSound : warnSounds) {
            String warnSoundOtherId = warnSound.getAudioId();
            warnSoundService.updateWarnSoundOtherStatus(warnSoundOtherId);
        }
        int state = warnSoundService.updateWarnSoundStatus(id);
        if (state > 0) {
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(), ReturnStateCode.SUCCEE.getMsg());
        } else {
            return new ReturnData(ReturnStateCode.FAILED.getCode(), ReturnStateCode.FAILED.getMsg());
        }
    }

    /**
     * 导入预警声音
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @OperLog(operModul = "预警音乐管理", operType = "5", operDesc = "导入预警声音")
    public ReturnData importFile(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//        boolean flag=false;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {

            MultipartFile file = entity.getValue();// 获取上传文件对象
            // 获取文件名
            String fileName = file.getOriginalFilename();

            if (!file.isEmpty()) {
                File newFile = new File(uploadWarnSoundUrl + File.separator + fileName);
                System.out.println(newFile);
                if (!newFile.exists()) {
                    WarnSound warnSound = new WarnSound();
                    warnSound.setAudioName(fileName.substring(0, fileName.lastIndexOf(".")));
                    warnSound.setDescrible(fileName.substring(0, fileName.lastIndexOf(".")) + "的说明");
                    warnSound.setStatus("0");
                    warnSound.setAudition("0");
                    warnSound.setPath(getWarnSoundUrl(fileName));
                    warnSoundService.save(warnSound);
                } else {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), "预警声音已存在,导入失败!");
                }
                try {
                    file.transferTo(newFile);
                } catch (Exception e) {
                    return new ReturnData(ReturnStateCode.FAILED.getCode(), "预警声音上传失败原因" + e.getMessage());
                } finally {
                    try {
                        file.getInputStream().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return new ReturnData(ReturnStateCode.SUCCEE.getCode(), "预警声音导入成功!");
            }
        }
        return null;
    }

    @RequestMapping(value = "/getWarnSoundUrl", method = RequestMethod.GET)
    public String getWarnSoundUrl(String fileName) {
        //获取预警声音上传根目录长度
        int uploadLength = upload.length();
        //获取预警声音路径长度
        int uploadFilesPdfLength = uploadWarnSoundUrl.length();
        String s = uploadWarnSoundUrl.substring(uploadLength, uploadFilesPdfLength);
        String productUrl = normalizeUrl(s + File.separator + fileName);
        // 获取预警声音的路径
        String path = ip + ":" + port + productUrl;
        return path;
    }

    // 正则化URL路径
    public String normalizeUrl(String path) {
        String placeholder = "6445BF55-95C4-41F9-8235-34CE3ED9146D";
        String result = path.replaceAll("\\\\+", "/");
        result = result.replaceAll("/+", "/");
        result = result.replaceAll("/+", placeholder);
        return result.replace(placeholder, "/");
    }
}
